﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace YJTTool.Core.Global
{
    /// <summary>
    /// 全局方法事件参数传输基类
    /// </summary>
    public class GlobalMethodEventParameter
    {
        private readonly Dictionary<string, object> _parameters = new();

        // 基础信息 --------------------------------------------------
        /// <summary>
        /// 事件/方法名称 (对应 GlobalMethodNames 中的常量)
        /// </summary>
        public string MethodName { get; set; }

        /// <summary>
        /// 事件触发时间戳
        /// </summary>
        public DateTime Timestamp { get; } = DateTime.UtcNow;

        // 状态信息 --------------------------------------------------
        /// <summary>
        /// 操作是否成功
        /// </summary>
        public bool IsSuccess { get; set; }

        /// <summary>
        /// 错误信息（当 IsSuccess 为 false 时使用）
        /// </summary>
        public Exception Error { get; set; }

        // 上下文信息 ------------------------------------------------
        /// <summary>
        /// 用户标识（可存储用户ID、用户名等）
        /// </summary>
        public string UserIdentity { get; set; }

        /// <summary>
        /// 来源模块/组件名称
        /// </summary>
        public string SourceModule { get; set; }

        /// <summary>
        /// 传递的值
        /// </summary>
        public object Value { get; set; }

        // 扩展参数存取方法 ------------------------------------------
        /// <summary>
        /// 添加扩展参数
        /// </summary>
        public void AddParameter<T>(string key, T value)
        {
            if (string.IsNullOrWhiteSpace(key))
                throw new ArgumentException("Parameter key cannot be null or empty");

            _parameters[key] = value;
        }

        /// <summary>
        /// 获取扩展参数（强类型版本）
        /// </summary>
        public T GetParameter<T>(string key, T defaultValue = default)
        {
            if (_parameters.TryGetValue(key, out var value) && value is T typedValue)
                return typedValue;

            return defaultValue;
        }

        /// <summary>
        /// 检查参数是否存在
        /// </summary>
        public bool HasParameter(string key) => _parameters.ContainsKey(key);

        // 构造函数重载 ----------------------------------------------
        public GlobalMethodEventParameter() { }

        public GlobalMethodEventParameter(string methodName)
        {
            MethodName = methodName ?? throw new ArgumentNullException(nameof(methodName));
        }

        public GlobalMethodEventParameter(string methodName, IDictionary<string, object> parameters)
            : this(methodName)
        {
            foreach (var kvp in parameters)
            {
                AddParameter(kvp.Key, kvp.Value);
            }
        }
    }
}
